<script>
  import Title from '@lib/Title.svelte'
  import { pop, push } from 'svelte-spa-router'
  import courses from '@/store'

  export let params = {}

  const curCourses = $courses.find(c => '' + c.id === '' + params.id)
  console.log('id---', curCourses)
  const onClose = () => {
    pop()
    // push('/')
  }

  const onAdd = () => {
    if (curCourses && curCourses.id) {
      const addArr = $courses.filter(c => c.id !== curCourses.id)
      $courses = [{ id: params.id, name, amount }, ...addArr]
    } else {
      const id = Math.floor(Math.random() * 10000000)
      $courses = [{ id, name, amount }, ...$courses]
    }

    push('/')
  }

  let name = curCourses?.name ?? ''
  let amount = curCourses.amount ?? 0
  $: canAdd = !!name && !!amount

  const title = curCourses ? '编辑课程' : '添加课程'
</script>

<section class="form">
  <Title {title} />
  <form class="course-form">
    <div class="form-control">
      <label for="name">课程名称</label>
      <input type="text" id="name" bind:value={name} />
    </div>
    <div class="form-control">
      <label for="amount">课程价格</label>
      <input type="number" id="amount" bind:value={amount} />
    </div>

    {#if !canAdd}
      <p class="form-empty">请填写表单信息</p>
    {/if}
    <button type="submit" class="btn btn-block" class:disabled={!canAdd} disabled={!canAdd} on:click|preventDefault={() => onAdd()}>{title}</button>
    <button class="close-btn" on:click|preventDefault={() => onClose()}>
      <i class="fa fa-times" />关闭
    </button>
  </form>
</section>
